package com.sjf.JavaNIO.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * ServerSocketChannelDemo本身不进行数据的传输，在于监听SocketChannel连接的传入
 *
 * @author <huangtang>
 * @since 2022/4/13 17:22
 **/
public class ServerSocketChannelDemo {

    public static void main ( String[] args ) throws Exception {
        //端口号
        int port = 8888;

        //创建一个buffer
        ByteBuffer buffer = ByteBuffer.wrap ("hello atguigu".getBytes ());

        //打开ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open ();
        //建立起监听8888端口是否有ServerSocket连接
        ssc.socket ().bind (new InetSocketAddress (port));
        //设置非阻塞模式
        //会一直监听对应端口的SocketChannel连接
        ssc.configureBlocking (false);
        //记录等待的次数
        int count = 0;
        //监听是否有新地连接传入
        while (true) {
            System.out.println ("Waiting for connections");
            SocketChannel sc = ssc.accept ();
            if ( sc == null ) {
                //没有新的连接传入
                System.out.println ("没有新的连接传入,监听等待 " + count++ + " 次");
                Thread.sleep (2000);
            } else {
                //有连接进行传入
                System.out.println ("Incoming connection from " + sc.socket ().getRemoteSocketAddress ());
                buffer.rewind (); //指针指向缓冲区的开始位置
                sc.write (buffer); //将buffer缓冲区的数据写入到socket中
                sc.close ();
                ssc.close ();
            }
        }
    }
}
